package com.xiuxian.dao.impl;

import com.xiuxian.dao.UserDao;
import com.xiuxian.model.User;
import com.xiuxian.util.MybatisUtils;
import org.apache.ibatis.session.SqlSession;

import java.util.ArrayList;
import java.util.List;

public class UserDaoImpl implements UserDao {
    @Override
    public List<User> findAllUsernameLike(String username) {
        SqlSession sqlSession = null;
        List<User> userList = new ArrayList<>();
        try {
            sqlSession = MybatisUtils.getSqlSession();
            userList = sqlSession.selectList("userDao.selectlikeusername",username);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            MybatisUtils.close(sqlSession);
        }
        return userList;
    }

    @Override
    public int save(User user) {
        SqlSession sqlSession = null;
        int count = 0;
        try {
            sqlSession = MybatisUtils.getSqlSession();
            count=  sqlSession.insert("userDao.insertUser",user);
            sqlSession.commit();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            MybatisUtils.close(sqlSession);
        }

        return  count;
    }

    @Override
    public int update(User user) {
        SqlSession sqlSession = null;
        int count = 0;
        try {
            sqlSession = MybatisUtils.getSqlSession();
            count=  sqlSession.update("userDao.updateUser",user);
            sqlSession.commit();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            MybatisUtils.close(sqlSession);
        }

        return  count;
    }

    @Override
    public int delete(Integer id) {
        SqlSession sqlSession = null;
        int count = 0;
        try {
           sqlSession = MybatisUtils.getSqlSession();
           count=  sqlSession.delete("userDao.deletebyid",id);
           sqlSession.commit();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            MybatisUtils.close(sqlSession);
        }

        return  count;
    }
}
